extends CharacterBody3D

@onready var gun_model = $Camera3D/gun_model
@onready var SPEED = 5
const BULLET_3D = preload("res://game3d_2/scenes/bullet3D.tscn")

func  _ready():
	pass
	# Input.mouse_mode = Input.MOUSE_MODE_CAPTURED

func _unhandled_input(event):
	if event is InputEventMouseMotion:
		rotation_degrees.y -= event.relative.x * 0.5
		%Camera3D.rotation_degrees.x -= event.relative.y * 0.2
		%Camera3D.rotation_degrees.x = clamp(
			%Camera3D.rotation_degrees.x, -60.0, 60.0
		)
	elif event.is_action_pressed("ui_cancel"):
		# Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
		pass

func _physics_process(delta):
	var input_direction_2d = Input.get_vector("move_left", "move_right", "move_up", "move_down")
	var input_direction_3d = Vector3(
		input_direction_2d.x, 0.0, input_direction_2d.y
	)
	var direction = transform.basis * input_direction_3d
	velocity.x = SPEED * direction.x
	velocity.z = SPEED * direction.z

	velocity.y -= 20.0 * delta
	if Input.is_action_just_pressed("jump") and is_on_floor():
		velocity.y = 10.0
	elif Input.is_action_just_released("jump") and velocity.y > 0.0:
		velocity.y = 0.0   
	move_and_slide()
	
	if Input.is_action_pressed("hit") and %Timer.is_stopped():
		shoot_bullet()

func shoot_bullet() -> void:
	var new_bullet = BULLET_3D.instantiate()
	%Marker3D.add_child(new_bullet)
	new_bullet.global_transform = %Marker3D.global_transform
	%Timer.start()
	$AudioStreamPlayer.play()
